import { Component, EventEmitter, Input, Output } from '@angular/core';
import { NotifyService } from '../../../service/notify.service';
import { Host } from '../../../service/config.service';
import { ClientSession, SessionService } from '../../../service/session.service';
import { fromEvent } from 'rxjs';
import { MyTabPanel } from '../../public/tabview/tabview.component';

@Component({
  selector: 'app-base-tab',
  templateUrl: './base-tab.component.html',
  styleUrls: ['./base-tab.component.css']
})
export abstract class BaseTabComponent {

  session: ClientSession;
  @Input() host: Host;
  @Input() tabIndex: number;
  @Input() type: string;
  @Output() onStateChange = new EventEmitter<string>();
  isActive: boolean;

  state: "CONNECTING" | "CONNECTED" | "ERROR";
  newSession(onOpen, onData, onError) {
    this.state = "CONNECTING";
    this.onStateChange.emit('CONNECTING');
    if (this.session) this.session.kill();
    this.session = this.sessionService.newSession(this.type, this.host);
    this.session.opened$.subscribe((path: any) => {
      //console.log("recv CONNECTED")
      this.state = "CONNECTED";
      this.onStateChange.emit('CONNECTED');
      if (onOpen) onOpen(path);
    })
    this.session.output$.subscribe(data => {
      //console.log("recv data")
      //if (onData && this.state == 'CONNECTED') onData(data);
      if (onData) onData(data);
    })
    this.session.error$.subscribe(error => {
      //console.log("recv ERROR")
      this.session.kill();
      this.session = null;
      this.state = "ERROR"
      this.onStateChange.emit('ERROR');
      if (onError) onError(error);
    })
    //this.session.start();
  }
  abstract onTabActive();
  abstract onWindowResize();
  constructor(tabPanel: MyTabPanel, protected sessionService: SessionService, protected notify: NotifyService) {
    tabPanel.active$.subscribe(() => {
      this.isActive = true;
      this.onTabActive();
    })
    /*this.notify.onMainTabIndexChange((index) => {
      if (index == this.tabIndex) {
        this.isActive = true;
        this.onTabActive();
      } else {
        this.isActive = false;
      }
    })*/
    fromEvent(window, 'resize').subscribe((event) => {
      if (this.isActive) {
        this.onWindowResize();
      }
    })
  }
}
